package com.android.aqq;

import java.util.Iterator;
import java.util.List;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.android.aqq.bean.ChatState;
import com.android.aqq.bean.QQBuddy;
import com.android.aqq.bean.QQGroup;
import com.android.aqq.bean.QQGroupMember;
import com.android.aqq.bean.QQMessage;
import com.android.aqq.util.Utils;

import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.in.ReceiveIMPacket;

public class GroupChatWindowActivity extends FlipActivity {
	private ChatState chatState; 
	private QQGroup mQQGroup;
	private TableLayout mTableLayout;
	private ScrollView mScrollView;
	private int positon = 0;
	private Menu mMenu;
	private ListView mMemberListView;
	private MemberListAdapter mMemberListAdapter;
	private EditText mEditText;
	private int myQQ;
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_chat_window);
		initFlipParam(R.id.flipper);
		
		mMemberListView = (ListView)findViewById(R.id.member_list);
		mMemberListView.setOnTouchListener(new OnTouchListener(){
			public boolean onTouch(View view, MotionEvent event) {
		        if (gestureDetector.onTouchEvent(event))
			        return true;
			    else
			    	return false;
			}
			
		});
		
		Intent intent = getIntent();
		mQQGroup = (QQGroup)intent.getSerializableExtra("QQ_GROUP");
		myQQ = intent.getIntExtra("MYQQ", 0);
		
		mMemberListAdapter = new MemberListAdapter(this);
		mMemberListView.setAdapter(mMemberListAdapter);
		
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 取消通知栏通知
        nm.cancel(aQQActivity.NOTIFICATION_QQGROUP_CHAT);
		
		if (aQQActivity.mChatStateMap == null || aQQActivity.user == null || !aQQActivity.user.isLoggedIn()) {
			finish();
			return;
		} 
		
		chatState = aQQActivity.mChatStateMap.get(mQQGroup.getClusterId());
		if (chatState == null) { //会话状态不存在
			finish();
			return;
		}
		chatState.setQQGroup(mQQGroup);
		chatState.resetNewMessageCount();
		
		//设置标题
		setTitle(mQQGroup.getName());
		
		
		//绑定handler
		aQQActivity.removeHandler(mQQGroup.getClusterId());
		aQQActivity.bindHandler(mQQGroup.getClusterId(), handler);
		
		mTableLayout = (TableLayout)findViewById(R.id.TableLayout02);
		mScrollView = (ScrollView)findViewById(R.id.ScrollView01);
		mTableLayout.setOnTouchListener(new OnTouchListener(){
			public boolean onTouch(View view, MotionEvent event) {
		        if (gestureDetector.onTouchEvent(event))
			        return true;
			    else
			    	return false;
			}
			
		});
		
		mScrollView.setOnTouchListener(new OnTouchListener(){
			public boolean onTouch(View view, MotionEvent event) {
		        if (gestureDetector.onTouchEvent(event))
			        return true;
			    else
			    	return false;
			}
			
		});
		
		final Button sendButton =(Button) findViewById(R.id.ButtonSend);
		mEditText = (EditText) findViewById(R.id.TextSend);
		sendButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				if (mEditText.getText().length()>0) {
					sendMessage();
				}
			}
		});
		
		Iterator<QQMessage> iterator = chatState.getMessageQueue().iterator();
		while(iterator.hasNext()) {
			QQMessage message = iterator.next();
			if (message.getSender() == myQQ) {
				insertChat(message.getMessage(), true);
			} else {
				insertChat(message.getMessage(), false);
			}
			
		}
	}
	
	private void sendMessage() {
		String message = mEditText.getText().toString();
		aQQActivity.client.im_SendCluster(mQQGroup.getClusterId(), message);
//			message = "我：["+ DateFormat.format("kk:mm", Calendar.getInstance()) + "]\n" + message;
//			insertChat(message);
		mEditText.setText("");
//			chatState.addMessage(message);
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	switch(msg.what) {
        	case QQEvent.IM_CLUSTER_RECEIVED:
        		QQEvent event = (QQEvent) msg.obj;
        		ReceiveIMPacket packet = (ReceiveIMPacket) event.getSource();
        		String message = mQQGroup.getMember(packet.clusterIM.sender).toString() + "：["+ DateFormat.format("kk:mm", packet.clusterIM.sendTime) + "]\n" + packet.clusterIM.message;
				if (packet.clusterIM.sender == myQQ) {
					insertChat(message, true);
				} else {
					insertChat(message, false);
				}
        		
        		break;
        	case -1:
        		finish();
        		break;
        	}
        }
	};
	
	private void insertChat(String message, boolean me) {
		TextView v = new TextView(GroupChatWindowActivity.this);
		v.setText(message.replaceAll("\r","\n"));
		TableRow row = new TableRow(GroupChatWindowActivity.this);
		TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
//		layoutParams.span = 2;
		layoutParams.column=1;
		v.setLayoutParams(layoutParams);
		v.setTextSize(18);
		v.setPadding(3, 3, 3, 3);
		v.setSingleLine(false);
		if (me) {
			row.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_text_highlight_background));
		} else {
			row.setBackgroundDrawable(getResources().getDrawable(R.drawable.chat_text_background));
		}
		v.setTextColor(getResources().getColor(android.R.color.black));
		row.addView(v);
		mTableLayout.addView(row, positon);
		handler.post(scrollToBottom);
		positon ++;
	}
	
	private Runnable scrollToBottom = new Runnable() {  
        public void run() {  
            int off = mTableLayout.getMeasuredHeight() - mScrollView.getHeight();  
            if (off > 0) {  
                mScrollView.scrollTo(0, off);  
            }                         
        }  
	};
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
		chatState.resetNewMessageCount();
	}

	@Override
	protected void onStart() {
		super.onStart();
	} 
 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    	 mMenu = menu;
         
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu_chat, menu);
         
         return true;
    }
    
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) { 
    	case R.id.menu_end_conversation:
    		aQQActivity.mChatStateMap.remove(mQQGroup.getClusterId());
    		setResult(RESULT_CANCELED);
    		finish();
            break;
    	case R.id.menu_change_conversation:
    		Intent intent = new Intent(this, ChatDashboardActivity.class);
    		intent.putExtra("CHAT_ID", mQQGroup.getClusterId() );
    		startActivityForResult(intent, 3);
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    
	/*自定义布局组件中用于显示数据的组件类**/
	public class ViewHolder {
		TextView mNick;
		TextView mQQ;
		TextView mStatus;
		ImageView mUserHead;
		ImageView mStatusIcon;
	}
    
	public class MemberListAdapter extends BaseAdapter {
		private Context mcContext;
		private LayoutInflater mInflater;
		private List<QQGroupMember> mMemberData;

		public MemberListAdapter(Context context) {
			this.mcContext = context;
			mInflater = LayoutInflater.from(this.mcContext);
			mQQGroup.sortMembers();
			mMemberData = mQQGroup.getMembers();
		} 
		
		public int getCount() {
			return mMemberData.size();
		}

		public QQGroupMember getItem(int pos) {
			return mMemberData.get(pos);
		}

		public long getItemId(int pos) {
			return pos;
		}

		public View getView(int pos, View convertView, ViewGroup vg) {
        	final ViewHolder holder;
        	if (convertView == null) {
        	    //使用XML文件填充整个布局
        	    convertView = mInflater.inflate(R.layout.user_list, null);
        	    holder = new ViewHolder();//生成存放数据的组件模型
        	    holder.mNick = (TextView) convertView.findViewById(R.id.nick);
        	    holder.mStatus = (TextView) convertView.findViewById(R.id.status);
        	    holder.mUserHead = (ImageView) convertView.findViewById(R.id.user_head);
//        	    holder.mStatusIcon = (ImageView) convertView.findViewById(R.id.status_icon);
        	    convertView.setTag(holder); //将存放数据的组件模型加入到整个View视图中
        	} else {
        	     holder = (ViewHolder) convertView.getTag();
        	}
        	QQGroupMember member = getItem(pos);
    		byte status = member.getStatus();
        	holder.mNick.setText(member.toString());
        	holder.mStatus.setText(Utils.getStatus(status));
        	
        	setListItemView(holder, status);
        	
//        	holder.mUserHead.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.delete));
        	holder.mUserHead.setOnClickListener(new OnClickListener(){
        	     public void onClick(View v) {
//					holder.mNick.setBackgroundColor(Color.WHITE);
//					holder.mUserHead.setVisibility(View.VISIBLE);
				}
			});
			return convertView;

		}
	}
	
    private void setListItemView(final ViewHolder holder, byte status) {
    	switch (status) {
    	case QQ.QQ_STATUS_ONLINE:
    		holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_online));
    		holder.mNick.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
			holder.mStatus.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
    		break;
    	case QQ.QQ_STATUS_QME:
    		holder.mNick.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
			holder.mStatus.setTextColor(getResources().getColor(android.R.color.primary_text_dark));
			holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_qme));
    		break;
    	case QQ.QQ_STATUS_OFFLINE:
    		holder.mNick.setTextColor(getResources().getColor(android.R.color.secondary_text_dark));
			holder.mStatus.setTextColor(getResources().getColor(android.R.color.secondary_text_dark));
			holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_offline));
    		break;
    	case QQ.QQ_STATUS_AWAY:
    		holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_away));
    	case QQ.QQ_STATUS_BUSY:
    		holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_busy));
    	case QQ.QQ_STATUS_QUIET:
    		holder.mUserHead.setImageDrawable(getResources().getDrawable(R.drawable.head_quiet));
    	default:
    		holder.mNick.setTextColor(getResources().getColor(android.R.color.secondary_text_dark));
			holder.mStatus.setTextColor(getResources().getColor(android.R.color.secondary_text_dark));
    		break;
    	}
	}
    
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 3) {
			if (resultCode == RESULT_OK) {
				int id = data.getIntExtra("CHAT_ID", 0);
				if (id!=0) {
					ChatState chat = aQQActivity.mChatStateMap.get(id);
					if (chat.getType() == 1) {
						QQBuddy buddy = chat.getBuddy();
						startActivity(new Intent(this, ChatWindowActivity.class).putExtra("FRIEND", buddy).putExtra("MYQQ", myQQ));
						finish();
					} else {
						QQGroup group = chat.getQQGroup();
						startActivity(new Intent(this, GroupChatWindowActivity.class).putExtra("QQ_GROUP", group).putExtra("MYQQ", myQQ));
						finish();
					}
					
				}
			}
        }
	}
}
